package zqkcom.atguigu.service.impl;


import zqkcom.atguigu.bean.*;
import zqkcom.atguigu.dao.BookDao;
import zqkcom.atguigu.dao.OrderDao;
import zqkcom.atguigu.dao.OrderItemDao;
import zqkcom.atguigu.dao.impl.BookDaoImpl;
import zqkcom.atguigu.dao.impl.OrderDaoImpl;
import zqkcom.atguigu.dao.impl.OrderItemDaoImpl;
import zqkcom.atguigu.service.OrderService;
import zqkcom.atguigu.servlet.BaseServlet;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl  implements OrderService {
    OrderDao orderDao = new OrderDaoImpl();
    OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();


    @Override
    public String checkOut(Cart cart, User user) {
        /**
         * 结账：
         *  1、保存订单
         *  2、保存订单项  -->改错
         *  3、更新库存和销量
         */
        String orderId = System.currentTimeMillis()+"" ;

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = sdf.format(date);

        Order order = new Order(orderId,createTime,cart.getTotalCount(),cart.getTotalAmount(),0,user.getId());

        orderDao.saveOrder(order);

        List<CartItem> cartItemList = cart.getCartItemList();

        for (CartItem cartItem : cartItemList) {
            Book book = cartItem.getBook();
            OrderItem orderItem = new OrderItem(null, book.getTitle(), book.getAuthor(), book.getPrice(), book.getImgPath(), cartItem.getCount(), cartItem.getAmount(), orderId);

            orderItemDao.saveOrderItem(orderItem);

            bookDao.updateSalesAndStock(book.getId(),cartItem.getCount());
        }
        return orderId;
    }

    @Override
    public List<Order> getMyOrder(Integer userId) {
        return orderDao.getMyOrder(userId);
    }

    @Override
    public List<Order> getAllOrder() {
        return orderDao.getAllOrder();
    }

    @Override
    public List<OrderItem> getDetails(String orderId) {
        return orderItemDao.getDetails(orderId);
    }

    @Override
    public void sendOrder(String orderId) {
         orderDao.updateStatus(orderId,1);
    }

    @Override
    public void takeOrder(String orderId) {
        orderDao.updateStatus(orderId,2);
    }
}
